using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class BuildTool : Editor
{
    [MenuItem("Tools/Build Windows Bundle")]
    static void BundleWindowsBuild()
    {
        Build(BuildTarget.StandaloneWindows);
    }
    [MenuItem("Tools/Build Android Bundle")]
    static void BundleAndroidBuild()
    {
        Build(BuildTarget.Android);
    }
    [MenuItem("Tools/Build iPhone Bundle")]
    static void BundleiPhoneBuild()
    {
        Build(BuildTarget.iOS);
    }
    static void Build(BuildTarget target)
    {
        List<AssetBundleBuild> assetBundleBuilds = new List<AssetBundleBuild>();//用于收集
        List<string> bundleInfos = new List<string>();//文件信息列表
        string[] files = Directory.GetFiles(PathUtil.BuildResourcesPath, "*", SearchOption.AllDirectories);
        /*Directory.GetDirectories获取所以文件夹，Directory.GetFiles获取所以文件，对应两种方式;(递归查找)
        一参为寻找路径，二参为匹配字符串（*为给的信号），三参为搜索选项 */
        //因为会把meta也找到，需要去掉meta文件
        for (int i = 0; i < files.Length; i++)
        {
            if (files[i].EndsWith(".meta")) continue;
            Debug.Log("files" + files[i]);
            AssetBundleBuild assetBundle = new AssetBundleBuild();//需要assetNames(相对于根目录路径“Assets/...”)和assetBundleName(文件名加后缀)
            string fileName = PathUtil.GetStandardPath(files[i]);//规范路径

            string assetName = PathUtil.GetUnityPath(fileName);
            assetBundle.assetNames = new string[] { assetName };//Unity相对目录
            string bundleName = fileName.Replace(PathUtil.BuildResourcesPath, "").ToLower();//去掉.../BuildResources

            bundleName = Path.GetFileName(bundleName); // 获取文件名

            assetBundle.assetBundleName = bundleName + ".ab";//需要后缀
            assetBundleBuilds.Add(assetBundle);
            //添加文件和依赖信息
            List<string> dependenceInfo = GetDependence(assetName);
            string bundleInfo = assetName + "|" + bundleName + ".ab";
            if (dependenceInfo.Count > 0)
                bundleInfo = bundleInfo + "|" + string.Join("|", dependenceInfo);
            //添加MD5
            string md5Info = MD5Generator.GetMD5HashFromFile(fileName);
            bundleInfo = bundleInfo + "$" + md5Info;
            bundleInfos.Add(bundleInfo);
        }


        if (Directory.Exists(PathUtil.BundleOutPath))
        {
            Directory.Delete(PathUtil.BundleOutPath, true);//true表示需要递归删除(子文件夹的子文件）
        }
        Directory.CreateDirectory(PathUtil.BundleOutPath);
        BuildPipeline.BuildAssetBundles(PathUtil.BundleOutPath, assetBundleBuilds.ToArray(), BuildAssetBundleOptions.None, target);
        /*一参为输出路径，二参为数组,三为压缩格式(None表示默认),四表示目标平台*/

        File.WriteAllLines(PathUtil.BundleOutPath + "/" + AppConst.FileListName, bundleInfos);
        //添加版本号
        File.AppendAllText(PathUtil.BundleOutPath + "/" + AppConst.FileListName, Environment.NewLine + "0.0.1");

        AssetDatabase.Refresh();
    }

    static List<string> GetDependence(string curFile)
    {   //获取依赖文件列表
        List<string> dependence = new List<string>();
        string[] files = AssetDatabase.GetDependencies(curFile);
        dependence = files.Where(file => !file.EndsWith(".cs") && !file.Equals(curFile)).ToList();//排除一些
        return dependence;
    }
}
